<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;

class RolesController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->middleware(function ($request, $next) {

            $action = request()->route()->getActionMethod();

            if (in_array($action, ['edit', 'update', 'destroy', 'editpermission', 'updatepermission'])) {
                if ($request->role == 1) {
                    session()->flash('danger', '超级管理员角色不允许操作');
                    return back();
                }
            }
            return $next($request);
        });
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $roles = Role::query();
        $key = $request->input('key', '');
        if (!empty($key)) {
            $roles = $roles->where('name', 'like', '%' . $key . '%')
                ->orWhere('display_name', 'like', '%' . $key . '%')
                ->orWhere('description', 'like', '%' . $key . '%');
        }
        $roles = $roles->paginate(10);
        return view('admin.roles.index', compact('roles', 'key'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.roles.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $this->validate($request, [
            'name' => 'required|unique:roles|max:50',
            'display_name' => 'nullable|unique:roles|max:50',
            'description' => 'nullable|max:191'
        ]);

        $admin = new Role;
        $admin->name = $request->name;
        $admin->display_name = $request->display_name;
        $admin->description = $request->description;

        if ($admin->save()) {
            session()->flash('success', '保存成功');
            return redirect()->route('roles.index');
        } else {
            session()->flash('danger', '保存失败');
            return redirect()->back();
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = Role::find($id);
        return view('admin.roles.edit', compact('role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'nullable|unique:roles|max:50',
            'display_name' => 'nullable|unique:roles|max:50',
            'description' => 'nullable|max:191'
        ]);

        $admin = Role::find($id);
        $request->filled('name') && $admin->name = $request->name;
        $request->filled('display_name') && $admin->display_name = $request->display_name;
        $request->filled('description') && $admin->description = $request->description;

        if ($admin->save()) {
            session()->flash('success', '保存成功');
            return redirect()->route('roles.index');
        } else {
            session()->flash('danger', '保存失败');
            return redirect()->back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::find($id);
        if ($role->delete()) {
            session()->flash('success', '删除成功');
        } else {
            session()->flash('danger', '删除失败');
        }
        return back();
    }

    /**
     * 修改角色权限节点
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editpermission($id)
    {
        $Tree = Permission::where('is_show', 1)->orderBy('sort')->get(['id', 'pid as pId', 'display_name as name'])->toArray();
        $perms_arr = \DB::table('permission_role')->where('role_id', $id)->pluck('permission_id')->toArray();

        $permissionTree = [];
        foreach ($Tree as $key => $val) {
            if ($val['pId'] == 0 || in_array($val['pId'], array_column($Tree, 'id'))) {
                if (in_array($val['id'], $perms_arr)) {
                    $val['checked'] = true;
                }
                $val['open'] = true;
                $permissionTree[] = $val;
            }
        }
        return view('admin.roles.editpermission', compact('permissionTree', 'id'));
    }

    /**
     * 修改角色权限节点提交
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updatepermission(Request $request, $id)
    {
        $this->validate($request, [
            'perms_id' => 'required|array',
        ]);
        $role = Role::find($id);
        $flag = $role->perms()->sync($request->perms_id);

        if ($flag) {
            session()->flash('success', '保存成功');
            return redirect()->route('roles.index');
        } else {
            session()->flash('danger', '保存失败');
            return redirect()->back();
        }
    }
}
